home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / gd25s.zip / CMP.C < prev    next >
C/C++ Source or Header  |  1993-10-08  |  14KB  |  544 lines

  1. /* cmp -- compare two files.
  2.    Copyright (C) 1990, 1991, 1992, 1993 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* Written by Torbjorn Granlund and David MacKenzie. */
  19.  
  20. #include "system.h"
  21. #include <stdio.h>
  22. #include "getopt.h"
  23. #include "cmpbuf.h"
  24.  
  25. extern char const version_string[];
  26.  
  27. #if __STDC__ && defined (HAVE_VPRINTF)
  28. void error (int, int, char const *, ...);
  29. #else
  30. void error ();
  31. #endif
  32. VOID *xmalloc PARAMS((size_t));
  33.  
  34. static int cmp PARAMS((void));
  35. static off_t file_position PARAMS((int));
  36. static size_t block_compare PARAMS((char const *, char const *));
  37. static size_t block_compare_and_count PARAMS((char const *, char const *, long *));
  38. static size_t block_read PARAMS((int, char *, size_t));
  39. static void printc PARAMS((int, unsigned));
  40. static void usage PARAMS((char const *));
  41.  
  42. /* Name under which this program was invoked.  */
  43. char const *program_name;
  44.  
  45. /* Filenames of the compared files.  */
  46. static char const *file[2];
  47.  
  48. /* File descriptors of the files.  */
  49. static int file_desc[2];
  50.  
  51. /* Read buffers for the files.  */
  52. static char *buffer[2];
  53.  
  54. /* Optimal block size for the files.  */
  55. static size_t buf_size;
  56.  
  57. /* Initial prefix to ignore for each file.  */
  58. static off_t ignore_initial;
  59.  
  60. /* Output format:
  61.    type_first_diff
  62.      to print the offset and line number of the first differing bytes
  63.    type_all_diffs
  64.      to print the (decimal) offsets and (octal) values of all differing bytes
  65.    type_status
  66.      to only return an exit status indicating whether the files differ */
  67. static enum
  68.   {
  69.     type_first_diff, type_all_diffs, type_status
  70.   } comparison_type;
  71.  
  72. /* If nonzero, print values of bytes quoted like cat -t does. */
  73. static int opt_print_chars;
  74.  
  75. static struct option const long_options[] =
  76. {
  77.   {"print-chars", 0, 0, 'c'},
  78.   {"ignore-initial", 1, 0, 'i'},
  79.   {"verbose", 0, 0, 'l'},
  80.   {"silent", 0, 0, 's'},
  81.   {"quiet", 0, 0, 's'},
  82.   {"version", 0, 0, 'v'},
  83.   {0, 0, 0, 0}
  84. };
  85.  
  86. static void
  87. usage (reason)
  88.      char const *reason;
  89. {
  90.   if (reason)
  91.     fprintf (stderr, "%s: %s\n", program_name, reason);
  92.  
  93.   fprintf (stderr, "\
  94. Usage: %s [-clsv] [-i chars] [--ignore-initial=bytes]\n\
  95.     [--print-chars] [--quiet] [--silent] [--verbose] [--version]\n\
  96.     from-file [to-file]\n", program_name);
  97.  
  98.   exit (2);
  99. }
  100.  
  101. int
  102. main (argc, argv)
  103.      int argc;
  104.      char *argv[];
  105. {
  106.   int c, i, exit_status;
  107.   struct stat stat_buf[2];
  108.  
  109.   program_name = argv[0];
  110.  
  111.   /* Parse command line options.  */
  112.  
  113.   while ((c = getopt_long (argc, argv, "ci:ls", long_options, 0))
  114.      != EOF)
  115.     switch (c)
  116.       {
  117.       case 'c':
  118.     opt_print_chars = 1;
  119.     break;
  120.  
  121.       case 'i':
  122.     ignore_initial = 0;
  123.     while (*optarg)
  124.       {
  125.         /* Don't use `atol', because `off_t' may be longer than `long'.  */
  126.         unsigned digit = *optarg++ - '0';
  127.         if (9 < digit)
  128.           usage ("--ignore-initial value must be a nonnegative integer");
  129.         ignore_initial = 10 * ignore_initial + digit;
  130.       }
  131.     break;
  132.  
  133.       case 'l':
  134.     comparison_type = type_all_diffs;
  135.     break;
  136.  
  137.       case 's':
  138.     comparison_type = type_status;
  139.     break;
  140.  
  141.       case 'v':
  142.     fprintf (stderr, "GNU cmp version %s\n", version_string);
  143.     break;
  144.  
  145.       default:
  146.     usage (0);
  147.       }
  148.  
  149.   if (optind == argc)
  150.     usage (0);
  151.  
  152.   file[0] = argv[optind++];
  153.   file[1] = optind < argc ? argv[optind++] : "-";
  154.  
  155.   if (optind < argc)
  156.     usage ("extra arguments");
  157.  
  158.   for (i = 0; i < 2; i++)
  159.     {
  160.       /* If file[1] is "-", treat it first; this avoids a misdiagnostic if
  161.      stdin is closed and opening file[0] yields file descriptor 0.  */
  162.       int i1 = i ^ (strcmp (file[1], "-") == 0);
  163.  
  164.       /* Two files with the same name are identical.
  165.      But wait until we open the file once, for proper diagnostics.  */
  166.       if (i && strcmp (file[0], file[1]) == 0)
  167.     exit (0);
  168.  
  169.       if (strcmp (file[i1], "-") == 0)
  170.     file_desc[i1] = STDIN_FILENO;
  171.       else
  172.     {
  173.       file_desc[i1] = open (file[i1], O_RDONLY);
  174.       if (file_desc[i1] < 0)
  175.         {
  176.           if (comparison_type == type_status)
  177.         exit (2);
  178.           else
  179.         error (2, errno, "%s", file[i1]);
  180.         }
  181.     }
  182.       if (fstat (file_desc[i1], &stat_buf[i1]) != 0)
  183.     error (2, errno, "%s", file[i1]);
  184.     }
  185.  
  186.   /* If the files are links to the same inode and have the same file position,
  187.      they are identical.  */
  188.  
  189.   if (stat_buf[0].st_dev == stat_buf[1].st_dev
  190.       && stat_buf[0].st_ino == stat_buf[1].st_ino
  191.       && file_position (0) == file_position (1))
  192.     exit (0);
  193.  
  194.   /* If output is redirected to "/dev/null", we may assume `-s'.  */
  195.  
  196.   if (comparison_type != type_status)
  197.     {
  198.       struct stat outstat, nullstat;
  199.  
  200.       if (fstat (STDOUT_FILENO, &outstat) == 0
  201.       && stat ("/dev/null", &nullstat) == 0
  202.       && outstat.st_dev == nullstat.st_dev
  203.       && outstat.st_ino == nullstat.st_ino)
  204.     comparison_type = type_status;
  205.     }
  206.  
  207.   /* If only a return code is needed,
  208.      and if both input descriptors are associated with plain files,
  209.      conclude that the files differ if they have different sizes.  */
  210.  
  211.   if (comparison_type == type_status
  212.       && S_ISREG (stat_buf[0].st_mode)
  213.       && S_ISREG (stat_buf[1].st_mode))
  214.     {
  215.       off_t s0 = stat_buf[0].st_size - file_position (0);
  216.       off_t s1 = stat_buf[1].st_size - file_position (1);
  217.  
  218.       if (max (0, s0) != max (0, s1))
  219.     exit (1);
  220.     }
  221.  
  222.   /* Get the optimal block size of the files.  */
  223.  
  224.   buf_size = buffer_lcm (STAT_BLOCKSIZE (stat_buf[0]),
  225.              STAT_BLOCKSIZE (stat_buf[1]));
  226.  
  227.   /* Allocate buffers, with space for sentinels at the end.  */
  228.  
  229.   for (i = 0; i < 2; i++)
  230.     buffer[i] = xmalloc (buf_size + sizeof (long));
  231.  
  232.   exit_status = cmp ();
  233.  
  234.   for (i = 0; i < 2; i++)
  235.     if (close (file_desc[i]) != 0)
  236.       error (2, errno, "%s", file[i]);
  237.   if (comparison_type != type_status)
  238.     {
  239.       if (ferror (stdout))
  240.     error (2, 0, "write error");
  241.       else if (fclose (stdout) != 0)
  242.     error (2, errno, "write error");
  243.     }
  244.   exit (exit_status);
  245.   return exit_status;
  246. }
  247.  
  248. /* Compare the two files already open on `file_desc[0]' and `file_desc[1]',
  249.    using `buffer[0]' and `buffer[1]'.
  250.    Return 0 if identical, 1 if different, >1 if error. */
  251.  
  252. static int
  253. cmp ()
  254. {
  255.   long line_number = 1;        /* Line number (1...) of first difference. */
  256.   long char_number = ignore_initial + 1;
  257.                 /* Offset (1...) in files of 1st difference. */
  258.   size_t read0, read1;        /* Number of chars read from each file. */
  259.   size_t first_diff;        /* Offset (0...) in buffers of 1st diff. */
  260.   size_t smaller;        /* The lesser of `read0' and `read1'. */
  261.   char *buf0 = buffer[0];
  262.   char *buf1 = buffer[1];
  263.   int ret = 0;
  264.   int i;
  265.  
  266.   if (ignore_initial)
  267.     for (i = 0; i < 2; i++)
  268.       if (file_position (i) == -1)
  269.     {
  270.       /* lseek failed; read and discard the ignored initial prefix.  */
  271.       off_t ig = ignore_initial;
  272.       do
  273.         {
  274.           size_t r = read (file_desc[i], buf0, (size_t) min (ig, buf_size));
  275.           if (!r)
  276.         break;
  277.           if (r == -1)
  278.         error (2, errno, "%s", file[i]);
  279.           ig -= r;
  280.         }
  281.       while (ig);
  282.     }
  283.  
  284.   do
  285.     {
  286.       read0 = block_read (file_desc[0], buf0, buf_size);
  287.       if (read0 == -1)
  288.     error (2, errno, "%s", file[0]);
  289.       read1 = block_read (file_desc[1], buf1, buf_size);
  290.       if (read1 == -1)
  291.     error (2, errno, "%s", file[1]);
  292.  
  293.       /* Insert sentinels for the block compare.  */
  294.  
  295.       buf0[read0] = ~buf1[read0];
  296.       buf1[read1] = ~buf0[read1];
  297.  
  298.       /* If the line number should be written for differing files,
  299.      compare the blocks and count the number of newlines
  300.      simultaneously.  */
  301.       first_diff = (comparison_type == type_first_diff
  302.             ? block_compare_and_count (buf0, buf1, &line_number)
  303.             : block_compare (buf0, buf1));
  304.  
  305.       char_number += first_diff;
  306.       smaller = min (read0, read1);
  307.  
  308.       if (first_diff < smaller)
  309.     {
  310.       switch (comparison_type)
  311.         {
  312.         case type_first_diff:
  313.           /* See Posix.2 section 4.10.6.1 for this format.  */
  314.           printf ("%s %s differ: char %ld, line %ld",
  315.               file[0], file[1], char_number, line_number);
  316.           if (opt_print_chars)
  317.         {
  318.           unsigned char c0 = buf0[first_diff];
  319.           unsigned char c1 = buf1[first_diff];
  320.           printf (" is %3o ", c0);
  321.           printc (0, c0);
  322.           printf (" %3o ", c1);
  323.           printc (0, c1);
  324.         }
  325.           putchar ('\n');
  326.           /* Fall through. */
  327.         case type_status:
  328.           return 1;
  329.  
  330.         case type_all_diffs:
  331.           do
  332.         {
  333.           unsigned char c0 = buf0[first_diff];
  334.           unsigned char c1 = buf1[first_diff];
  335.           if (c0 != c1)
  336.             {
  337.               if (opt_print_chars)
  338.             {
  339.               printf ("%6lu %3o ", char_number, c0);
  340.               printc (4, c0);
  341.               printf (" %3o ", c1);
  342.               printc (0, c1);
  343.               putchar ('\n');
  344.             }
  345.               else
  346.             /* See Posix.2 section 4.10.6.1 for this format.  */
  347.             printf ("%6ld %3o %3o\n", char_number, c0, c1);
  348.             }
  349.           char_number++;
  350.           first_diff++;
  351.         }
  352.           while (first_diff < smaller);
  353.           ret = 1;
  354.           break;
  355.         }
  356.     }
  357.  
  358.       if (read0 != read1)
  359.     {
  360.       if (comparison_type != type_status)
  361.         /* See Posix.2 section 4.10.6.2 for this format.  */
  362.         fprintf (stderr, "cmp: EOF on %s\n", file[read1 < read0]);
  363.  
  364.       return 1;
  365.     }
  366.     }
  367.   while (read0 == buf_size);
  368.   return ret;
  369. }
  370.  
  371. /* Compare two blocks of memory P0 and P1 until they differ,
  372.    and count the number of '\n' occurrences in the common
  373.    part of P0 and P1.
  374.    Assumes that P0 and P1 are aligned at long addresses!
  375.    If the blocks are not guaranteed to be different, put sentinels at the ends
  376.    of the blocks before calling this function.
  377.  
  378.    Return the offset of the first byte that differs.
  379.    Increment *COUNT by the count of '\n' occurrences.  */
  380.  
  381. static size_t
  382. block_compare_and_count (p0, p1, count)
  383.      char const *p0, *p1;
  384.      long *count;
  385. {
  386.   long l;        /* One word from first buffer. */
  387.   long const *l0, *l1;    /* Pointers into each buffer. */
  388.   char const *c0, *c1;    /* Pointers for finding exact address. */
  389.   long cnt = 0;        /* Number of '\n' occurrences. */
  390.   long nnnn;        /* Newline, sizeof (long) times.  */
  391.   int i;
  392.  
  393.   l0 = (long const *) p0;
  394.   l1 = (long const *) p1;
  395.  
  396.   nnnn = 0;
  397.   for (i = 0; i < sizeof (long); i++)
  398.     nnnn = (nnnn << CHAR_BIT) | '\n';
  399.  
  400.   /* Find the rough position of the first difference by reading long ints,
  401.      not bytes.  */
  402.  
  403.   while ((l = *l0++) == *l1++)
  404.     {
  405.       l ^= nnnn;
  406.       for (i = 0; i < sizeof (long); i++)
  407.     {
  408.       cnt += ! (unsigned char) l;
  409.       l >>= CHAR_BIT;
  410.     }
  411.     }
  412.  
  413.   /* Find the exact differing position (endianness independent).  */
  414.  
  415.   c0 = (char const *) (l0 - 1);
  416.   c1 = (char const *) (l1 - 1);
  417.   while (*c0 == *c1)
  418.     {
  419.       cnt += *c0 == '\n';
  420.       c0++;
  421.       c1++;
  422.     }
  423.  
  424.   *count += cnt;
  425.   return c0 - p0;
  426. }
  427.  
  428. /* Compare two blocks of memory P0 and P1 until they differ.
  429.    Assumes that P0 and P1 are aligned at long addresses!
  430.    If the blocks are not guaranteed to be different, put sentinels at the ends
  431.    of the blocks before calling this function.
  432.  
  433.    Return the offset of the first byte that differs.  */
  434.  
  435. static size_t
  436. block_compare (p0, p1)
  437.      char const *p0, *p1;
  438. {
  439.   long const *l0, *l1;
  440.   char const *c0, *c1;
  441.  
  442.   l0 = (long const *) p0;
  443.   l1 = (long const *) p1;
  444.  
  445.   /* Find the rough position of the first difference by reading long ints,
  446.      not bytes.  */
  447.  
  448.   while (*l0++ == *l1++)
  449.     ;
  450.  
  451.   /* Find the exact differing position (endianness independent).  */
  452.  
  453.   c0 = (char const *) (l0 - 1);
  454.   c1 = (char const *) (l1 - 1);
  455.   while (*c0 == *c1)
  456.     {
  457.       c0++;
  458.       c1++;
  459.     }
  460.  
  461.   return c0 - p0;
  462. }
  463.  
  464. /* Read NCHARS bytes from descriptor FD into BUF.
  465.    Return the number of characters successfully read.
  466.    The number returned is always NCHARS unless end-of-file or error.  */
  467.  
  468. static size_t
  469. block_read (fd, buf, nchars)
  470.      int fd;
  471.      char *buf;
  472.      size_t nchars;
  473. {
  474.   char *bp = buf;
  475.  
  476.   do
  477.     {
  478.       size_t nread = read (fd, bp, nchars);
  479.       if (nread == -1)
  480.     return -1;
  481.       if (nread == 0)
  482.     break;
  483.       bp += nread;
  484.       nchars -= nread;
  485.     }
  486.   while (nchars != 0);
  487.  
  488.   return bp - buf;
  489. }
  490.  
  491. /* Print character C, making nonvisible characters
  492.    visible by quoting like cat -t does.
  493.    Pad with spaces on the right to WIDTH characters.  */
  494.  
  495. static void
  496. printc (width, c)
  497.      int width;
  498.      unsigned c;
  499. {
  500.   register FILE *fs = stdout;
  501.  
  502.   if (c >= 128)
  503.     {
  504.       putc ('M', fs);
  505.       putc ('-', fs);
  506.       c -= 128;
  507.       width -= 2;
  508.     }
  509.   if (c < 32)
  510.     {
  511.       putc ('^', fs);
  512.       c += 64;
  513.       --width;
  514.     }
  515.   else if (c == 127)
  516.     {
  517.       putc ('^', fs);
  518.       c = '?';
  519.       --width;
  520.     }
  521.  
  522.   putc (c, fs);
  523.   while (--width > 0)
  524.     putc (' ', fs);
  525. }
  526.  
  527. /* Position file I to `ignore_initial' bytes from its initial position,
  528.    and yield its new position.  Don't try more than once.  */
  529.  
  530. static off_t
  531. file_position (i)
  532.      int i;
  533. {
  534.   static int positioned[2];
  535.   static off_t position[2];
  536.  
  537.   if (! positioned[i])
  538.     {
  539.       positioned[i] = 1;
  540.       position[i] = lseek (file_desc[i], ignore_initial, SEEK_CUR);
  541.     }
  542.   return position[i];
  543. }
  544.